#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : alien_invasion.py
# @Author: yaqiwe
# @Date  : 2021/10/18
# @Desc  : 游戏窗口以及游戏操作响应

import sys
import pygame
from settings import Settings
from ship import Ship
from bullet import Bullet


class AlienInvasion:

    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode(Settings.SCREEN_SIZE)
        pygame.display.set_caption('Alien Invasion')
        self.ship = Ship(self)
        self.is_full_screen = False
        # 创建子弹的分组
        self.bullets = pygame.sprite.Group()

    def run_game(self):
        # 游戏主体循环
        while True:
            self._check_events()
            self.ship.update()
            self.bullets.update()
            self._update_screen()

    def _check_events(self):
        """
        检查鼠标事件和键盘事件
        :return:
        """
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            # 检测到案件按下事件
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            # 检测到分开按键的操作
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)

    def _check_keydown_events(self, event):
        """
        按下按键的处理
        :rtype: object
        :param event:
        :return:
        """
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_F11:
            if not self.is_full_screen:
                self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        if event.key == pygame.K_SPACE:
            # 创建一个子弹并加入子弹分组
            self.bullets.add(Bullet(self))

    def _check_keyup_events(self, event):
        """
        放开按键的处理
        :param event:
        :return:
        """
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False

    def _update_screen(self):
        """
        更新屏幕事件
        :return:
        """
        self.screen.fill(Settings.BG_COLOR)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
            # 删除超出屏幕外的子弹对象
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)
        pygame.display.flip()


if __name__ == '__main__':
    AlienInvasion().run_game()
